package com.lry.basic.jvm.asm.demo1;

import aj.org.objectweb.asm.ClassReader;
import com.lry.basic.jvm.asm.utils.FileUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;


public class Test  {

    public static void main(String[] args) throws Exception {
        Test test = new Test();
        test.t1();
    }

    private void printClassInfo(byte[] b){
        ClassReader cr = new ClassReader(b);
        System.out.println("access="+cr.getAccess());
        System.out.println("className="+cr.getClassName());
        System.out.println("superName="+cr.getSuperName());
        System.out.println("interfaces="+ Arrays.toString(cr.getInterfaces()));
    }

    public void t1()throws Exception{
        String filepath = FileUtils.getFilePath("com/lry/HelloWorld.class");
        byte[] b = HelloWorld.g1();
        printClassInfo(b);

        FileUtils.writeBytes(filepath, b);

        Class clazz = Class.forName("com.lry.HelloWorld");
        Object obj = clazz.newInstance();

        System.out.println(clazz.getField("username").get(clazz));
        System.out.println(clazz.getField("age").get(clazz));

        Method method = clazz.getMethod("hello");
        method.invoke(obj);

        clazz.getMethod("say").invoke(obj);
        clazz.getMethod("testFor").invoke(obj);

        clazz.getDeclaredMethod("testIf",boolean.class).invoke(obj,false);
        clazz.getDeclaredMethod("testSwitch",int.class).invoke(obj,211);

        clazz.getMethod("testTry").invoke(obj);
    }



    public void t()throws Exception{

        String filepath = FileUtils.getFilePath("com/lry/HelloWorld.class");
        byte[] b = HelloWorld.genarate();
        FileUtils.writeBytes(filepath, b);


        Class clazz = Class.forName("com.lry.HelloWorld");
        Method method = clazz.getMethod("main",new Class[]{String.class});
        method.invoke(clazz,"1");
    }

}
